package poem_info2.JdbcUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.jdbc.core.JdbcTemplate;
import poem_info2.Task.Task2;
import poem_info2.domain.Poem;

import java.net.URL;
import java.util.List;
/**
 * https://so.gushiwen.cn/guwen/
 * 古诗文网 爬取古籍
 * */
/*解析每一首古诗页面的详情信息并保存*/
public class ParseDetailedUrl2 {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    public void parseUrl(String purl, List<Poem> ps, Poem p) throws Exception {
        //定义sql
        String sql = "insert into poems values(null, ?, ?, ?, ?, ?)";
        //解析详情页url
        Document document = null;
        try {
            document = Jsoup.parse(new URL(purl), 100000);
            p.setDynasty_id(15);
            //获取诗歌原文
            String content = null;
            content = document.select("div.contson").first().text();
            p.setContent(content);
            //判断该poem对象是否已经存在
            boolean flag = false;
            for (Poem poem: ps) {
                if (poem.equals(p)) {
                    flag = true;
                }
            }
            //如果存在
            if(flag) {
                System.out.println("[" + Task2.count++ + "]" + p.getTitle() + purl + "已存在！");
            } else {//如果不存在
                //存储数据
                template.update(sql, p.getTitle(), p.getDynasty_id(), p.getWriter_id(), content, purl);
                System.out.println("[" + Task2.count++ + "]" + p.getTitle() + purl +  "已保存！");
                ps.add(p);
            }
        } catch (Exception e) {
            System.out.println("[" + Task2.count++ + "]" + p.getTitle() + purl +  "无法解析！");
        }
    }
}
